<template>
  <view class="wrapper">
    <swiper class="swiper" circular :indicator-dots="false" :autoplay="true" :interval="3000" :duration="500">
      <swiper-item
          v-for="(item, index) in detail.image"
          :key="index"
          class="swpier-item"
      >
        <view class="image">
          <u--image lazy-load width="710rpx" height="710rpx" :fade="true" duration="450" mode="scaleToFill" :src="baseUrl + item.image.path" v-if="item.image"></u--image>
        </view>
      </swiper-item>
    </swiper>
    <!-- 防止打开sku底下滚动 -->
    <template v-if="!showPop">
      <view class="desc">
        <view class="title">{{ detail.title }}</view>
        <view class="title_sub">{{ detail.title_sub }}</view>
        <view class="price">￥{{ detail.price }}</view>
        <view class="price_old">￥{{ detail.price_old }}</view>
        <view class="stock">库存:{{ detail.stock }}</view>
        <view class="sell">已售: {{ detail.sell_count }}</view>
      </view>
      <view class="sku" v-if="haveSku" @click="openPop">
        <tag tag="规格" />
        <view class="value">
          <view class="sku-list">
            <view class="item" v-for="(item, index) in skuList" :key="index">
              {{ item }}
            </view>
          </view>
          <view class="select">
            <u-icon name="arrow-right" color="#333" size="24rpx"></u-icon>
          </view>
        </view>
      </view>
      <view class="freight">
        <tag tag="运费" />
        <view class="text">{{detail.freightText}}</view>
      </view>
      <view class="area" v-if="detail.area && detail.area.name">
        <view class="name" @click="clickArea(detail.area)">
          {{detail.area.name.name}}
        </view>
      </view>
      <view class="content">
        <tag tag="详情" />
        <view class="video" v-if="detail.video">
          <view class="video-control" v-if="!showVide" @click="showVide = !showVide">
            <u-icon name="play-right-fill" size="60" color="#ffffff"></u-icon>
          </view>
          <video
              v-show="showVide"
              :src="baseUrl + detail.video.url"
              controls></video>
        </view>
        <view class="text" v-html="detail.inText" v-if="detail.inText"></view>
        <view class="image-list" v-if="detail.inImages && detail.inImages.length > 0">
          <view class="image" v-for="(item, index) in detail.inImages" :key="index">
            <u--image lazy-load width="100%" height="100%" :fade="true" duration="450" mode="widthFix" :src="baseUrl + item"></u--image>
          </view>
        </view>
      </view>
      <view class="footer">
        <view class="icon">
          <view class="home" @click="goHome">
            <u-icon name="home"></u-icon>
            <view class="text">首页</view>
          </view>
          <view class="fav" @click="runFav">
            <u-icon name="star" v-if="!isFav"></u-icon>
            <u-icon name="star-fill" v-else></u-icon>
            <view class="text">收藏</view>
          </view>
          <view class="cart" @click="goCart">
            <u-icon name="shopping-cart"></u-icon>
            <view class="text">
              购物车
              <view class="count" v-if="cartCounter > 0">
                <u-badge type="error" max="99" :value="cartDisplay"></u-badge>
              </view>
            </view>
          </view>
        </view>
        <view class="button">
          <view class="cart" @click="handleCart">加入购物车</view>
          <view class="buy" @click="handleBuy">立即购买</view>
        </view>
      </view>
    </template>
    <!-- pop sku -->
    <u-popup @touchmove.prevent :show="showPop" :round="10" :duration="200" mode="bottom"  @close="closePop" @open="openPop">
      <view class="pop">
        <view class="reset" @click="popReset">重新选择</view>
        <view class="main">
          <view class="image">
            <image :src="baseUrl + currentImage"></image>
          </view>
          <view class="text">
            <view class="stock">库存: {{ currentStock }}</view>
            <view class="price">价格: <text>￥{{ currentPrice }}</text></view>
            <view class="quantity">
              <view class="sub" @click="subQuantity">-</view>
              <view class="value"><input v-model.number="selectedQuantity" @input="changeQuantity" /></view>
              <view class="add" @click="addQuantity">+</view>
            </view>
          </view>
        </view>
        <view class="selected-result" v-if="selectedText.length > 0">
          <view class="item">
            您选择了:
            <text>{{ selectedText.join(', ') }}</text>
          </view>
          <view class="item">
            总数量: <text>{{ selectedQuantity }}</text>
            <!--总数量: <text>{{ realTotal }}</text>-->
            总金额: <text>￥{{ totalPrice }}</text>
            <!--总金额: <text>￥{{ realPrice }}</text>-->
          </view>
        </view>
        <view class="sku-list">
          <view class="item" v-for="(item, index) in detail.skuName" :key="index">
            <view class="name">{{ item.name }}</view>
            <view class="value">
              <template v-for="(o, i) in item.values">
                <view
                    :key="i"
                    class="value-item"
                    v-if="allSkuList && allSkuList.includes(o.id)"
                    @click="selectSkuValue(o)"
                    :class="{'active': o.selected, 'disable': o.disabled}"
                >
                  {{ o.value }}
                  <template v-if="o.value.indexOf('-') > 0">
                    <text class="total"> | {{o.value | skuTotal}}</text>
                  </template>
                </view>
              </template>
            </view>
          </view>
        </view>
        <view class="button" v-if="clickType > 0" @click="popSubmit">{{ popButtonText }}</view>
      </view>
    </u-popup>
    <u-back-top bottom="150" :scroll-top="scrollTop" icon="arrow-up" :customStyle="{'opacity': '0.88'}"></u-back-top>
  </view>
</template>

<script>
import config from '../../config/config'
import base64 from '../../util/base64'
import Product from '../../api/product'
import Cart from '../../api/cart'
import Fav from '../../api/fav'
import Tag from './components/Tag'
const productModel = new Product()
const cartModel = new Cart()
const favModel = new Fav()
import { mapGetters } from 'vuex'

export default {
  components: {
    Tag
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  filters: {
    skuTotal(v) {
      let str = ''
      const list = v.split('-')
      if (list.length === 2) {
        const a = list[0].trim()
        const b = list[1].trim()
        str = +b - +a + 1
      }
      return str
    }
  },
  computed: {
    ...mapGetters({
      cartDisplay: 'Cart/showTotal',
      cartCounter: 'Cart/total',
    }),
    // 判断是否存在sku
    haveSku() {
      // sku 是设置的值， skuName是规格名称
      // console.log(this.detail.sku, this.detail.skuName)
      return this.detail.sku && this.detail.sku.length > 0
          && this.detail.skuName && this.detail.skuName.length > 0
    },
    // sku列表
    skuList() {
      return this.detail.skuName && this.detail.skuName.length > 0 ? this.detail.skuName.map(x => x.name) : []
    },
    // pop 按钮文字内容
    popButtonText() {
      let text = ''
      switch (this.clickType) {
        case 1:
          text = '添加到购物车'
          break
        case 2:
          text = '立即购买'
          break
        case 3:
          text = '发起拼团'
          break
        case 4:
          text = '参与此团'
          break
        case 5:
          text = '随机拼团'
          break
        default:
          text = ''
      }
      return text
    },
    allSkuList() {
      let list = []
      if (this.detail.sku && this.detail.sku.length > 0) {
        list = this.detail.sku.map(x => x.sku_values)
        const x = list.reduce((previous, current) => {
          return previous.concat(current)
        })
        // 把x转成int, 因为api传回来的是数字
        return x.map(x => +x)
      }
    },
    currentPrice() {
      let price = this.detail.price
      if (this.selectedList.length > 0) {
        price = this.whichSku.price
      }
      return price
    },
    currentStock() {
      let stock = this.detail.stock
      if (this.selectedList.length > 0) {
        stock = this.whichSku.stock
      }
      return stock
    },
    currentImage() {
      let image = ''
      if (this.detail.mainImage) {
        image = this.detail.mainImage.thumbnail_path
      }
      if (this.selectedList.length > 0) {
        if (this.whichSku && this.whichSku.image) {
          image = this.whichSku.image.thumbnail_path
        }
      }
      return image
    },
    totalPrice() {
      return (this.currentPrice * this.selectedQuantity).toFixed(2)
    },
    // 处理码段价格与数量
    // realTotal() {
    //   return this.selectedQuantity * this.realSelectedQuantity
    // },
    // realPrice() {
    //   return this.currentPrice * this.realTotal
    // }
  },
  watch: {
    // 监听选中的sku, 处理对应的sku
    selectedSku: {
      deep: true,
      handler(v) {
        // 这里是不太严格的, 为了对应老版sku(残缺的), 一样可以
        this.whichSku = v[0]
        console.log(v[0])
      }
    }
  },
  data() {
    return {
      // 视频遮挡问题
      showVide: false,
      scrollTop: 0,
      baseUrl: config.baseUrl,
      id: 0,
      detail: {},
      isFav: false,
      showPop: false,
      // 点击类型标识
      clickType: 1,
      // sku选择
      selectedList: [],
      selectedText: [],
      selectedSku: [],
      whichSku: {},
      selectedQuantity: 1,
      // 下单参数
      options: {},
      // 真实数量
      realSelectedQuantity: 1
    }
  },
  onLoad(options) {
    this.id = options.id
    // 分享
    /*#ifdef MP-WEIXIN*/
    // 微信小程序端执行的逻辑
    uni.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],
      success: res => {

      }
    })
    /*#endif*/
  },
  onShow() {
    this.fetchData()
    this.getCartTotal()
  },
  methods: {
    fetchData() {
      productModel.detail({ id: this.id }).then(response => {
        let { data } = response
        data = base64.parse(data)
        this.detail = data
        uni.setNavigationBarTitle({
          title: data.title
        })
        console.log(data)
        // 检查是否收藏
        this.checkFav()
      })
    },
    clickArea(area) {
      uni.navigateTo({
        url: `/sub_product/area/index?id=${area.area_id}`
      })
    },
    goHome() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    },
    goCart() {
      uni.switchTab({
        url: '/pages/cart/index'
      })
    },
    // 购物车数量
    getCartTotal() {
      this._isLogin().then(() => {
        cartModel.total().then(response => {
          let { data } = response
          data = base64.parse(data)
          this.$store.dispatch('Cart/set_change_list', data)
          // uni.setTabBarBadge({
          //   index: 2,
          //   text: this.$store.getters['Cart/showTotal']
          // })
        })
      }).catch(() => {
        // console.log('未登录')
      })
    },
    // 检查是否收藏
    checkFav() {
      this._isLogin().then(() => {
        favModel.checkFavorite({ id: this.id }).then(response => {
          let { data } = response
          data = base64.parse(data)
          this.isFav = !!data.is
        })
      }).catch(() => {
        // console.log('未登录')
      })
    },
    // 收藏操作
    runFav() {
      this._isLogin().then(() => {
        if (!this.isFav) {
          favModel.addFavorite({ id: this.id }).then(() => {
            this.isFav = true
            uni.showToast({
              icon: 'none',
              title: '收藏成功'
            })
          })
        } else {
          favModel.removeFavorite({ id: this.id }).then(() => {
            this.isFav = false
            uni.showToast({
              icon: 'none',
              title: '取消成功'
            })
          })
        }
      }).catch(() => {
        // 未登录
        this.isFav = !this.isFav
      })
    },
    // 判断登录
    _isLogin() {
      return new Promise((resolve, reject) => {
        const token = this.$store.getters['User/token']
        if (!token) {
          reject()
        } else {
          favModel.isLogin({ token }).then(response => {
            let { data } = response
            data = base64.parse(data)
            if (data.isLogin) {
              resolve()
            } else {
              // 没有登录
              reject()
            }
          })
        }
      })
    },
    // pop
    openPop() {
      this.showPop = true
    },
    closePop() {
      this.showPop = false
    },
    handleCart() {
      if (this.haveSku) {
        this.clickType = 1
        this.openPop()
      } else {
        this.addCart()
      }
    },
    handleBuy() {
      if (this.haveSku) {
        this.clickType = 2
        this.openPop()
      } else {
        this.buy()
      }
    },
    addCart() {
      cartModel.addCart({
        ...this.handleOptions()
      }).then(() => {
        uni.showToast({
          title: '添加成功',
          icon: 'success'
        })
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/cart/index'
          })
        }, 500)
      })
    },
    buy() {
      // 保存参数到store
      this.$store.dispatch('Order/set_params', this.handleOptions()).then(() => {
        const params = base64.encodeUrl(this.handleOptions())
        uni.navigateTo({
          url: `/sub_main/order/index?params=${params}`
        })
      })
    },
    // sku 值选择
    _selectedValues(appendText = false) {
      const list = []
      this.detail.skuName.forEach(x => {
        x.values.forEach(y => {
          if (y.selected) {
            if (appendText) {
              list.push({ id: y.id, text: y.value })
            } else {
              list.push(y.id)
            }
          }
        })
      })
      return list
    },
    // sku 选择
    selectSkuValue(o) {
      if (o.disabled && this.detail.skuName.length > 1) {
        return
      }
      // 1. [ 名称索引, 选中否 ]
      let skuNameIndex, selected
      this.detail.skuName.forEach((x, index) => {
        x.values.forEach(y => {
          if (+y.id === o.id) {
            this.$set(o, 'selected', !o.selected)
            skuNameIndex = index
            selected = o.selected
          }
        })
      })
      // console.log(this.detail.skuName, skuNameIndex, selected)
      // 2. [ 同名称下的值, 取消选中 ]
      if (skuNameIndex !== undefined) {
        this.detail.skuName[skuNameIndex].values.forEach(x => {
          if (selected && +x.id !== o.id) {
            this.$set(x, 'selected', undefined)
          }
        })
      }
      // 3. admin set
      const selectedValues = this._selectedValues(true)
      const list = this.detail.sku.filter(x => selectedValues.every(y => x.sku_values.includes(y.id + '')))
      // 保存选中的值
      this.selectedSku = list
      const listValues = []
      list.forEach(x => {
        x.sku_values.forEach(y => {
          listValues.push(y)
        })
      })
      this.detail.skuName.forEach(x => {
        x.values.forEach(y => {
          if (!listValues.includes(y.id + '')) {
            this.$set(y, 'disabled', true)
          } else {
            this.$set(y, 'disabled', undefined)
          }
        })
      })
      // 4 selected display
      this.selectedText = selectedValues.map(x => x.text)
      this.selectedList = selectedValues.map(x => x.id)
      // console.log(this.selectedList, this.selectedText, this.detail)
      // 处理码段数量
      // this.selectedText.forEach(x => {
      //   if (x.indexOf('-') > 0) {
      //     const n = x.split('-')
      //     const a = +n[0].trim()
      //     const b = +n[1].trim()
      //     this.realSelectedQuantity = b - a + 1
      //   }
      // })
    },
    subQuantity() {
      if (this.selectedQuantity > 1) {
        this.selectedQuantity--
      }
    },
    addQuantity() {
      if (this.selectedQuantity < this.currentStock) {
        this.selectedQuantity++
      }
    },
    popReset() {
      this.selectedQuantity = 1
      this.selectedList = []
      this.selectedText = []
      this.detail.skuName.forEach(x => {
        x.values.forEach(y => {
          this.$set(y, 'selected', undefined)
          this.$set(y, 'disabled', undefined)
        })
      })
    },
    changeQuantity() {
      if (isNaN(this.selectedQuantity) || +this.selectedQuantity < 1) {
        this.selectedQuantity = 1
      }
    },
    popSubmit() {
      if (this.selectedList.length < 1) {
        return uni.showToast({
          icon: 'none',
          title: '请选择规格'
        })
      }
      // 规格选择完整
      if (this.selectedList.length < this.detail.skuName.length) {
        return uni.showToast({
          icon: 'none',
          title: '规格请选择完成'
        })
      }
      if (isNaN(this.selectedQuantity)) {
        return uni.showToast({
          icon: 'none',
          title: '库存错误'
        })
      }
      if (this.selectedQuantity > this.currentStock) {
        return uni.showToast({
          icon: 'none',
          title: '库存不足'
        })
      }
      this.showPop = false
      const options = {
        quantity: this.selectedQuantity,
        // quantity: this.realTotal,
        price: this.currentPrice,
        product_sku_id: this.whichSku.id,
        selected_sku_value: this.selectedList,
        selected_sku_text: this.selectedText
        // selected_sku_text: encodeURI(base64.encode(this.selectedText))
      }
      // console.log(base64.encode(this.selectedText))
      this.options = options
      // console.log(this.clickType)
      if (this.clickType === 1) {
        this.addCart()
      }
      if (this.clickType === 2) {
        this.buy()
      }
    },
    // 下单参数处理
    handleOptions() {
      const isEmpty = Object.keys(this.options).length === 0
      if (isEmpty) {
        return {
          price: this.detail.price,
          product_id: this.id,
          quantity: 1
        }
      }
      return {
        ...this.options,
        product_id: this.id,
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$swiper_height: 710rpx;
.wrapper {
  padding: 20rpx 20rpx 110rpx 20rpx;
  background: $background_color;
  .swiper {
    height: $swiper_height;
    background: white;
    .image {
      //background: red;
      height: $swiper_height;
      border-radius: 10rpx;
      overflow: hidden;
      //display: flex;
      //align-items: center;
      image {
        width: 100%;
        height: 100%;
        display: block;
        margin: auto;
      }
    }
  }
  .desc {
    margin: 20rpx 0;
    padding: 20rpx;
    background: white;
    color: $main_text_color;
    border-radius: 10rpx;
    view {
      line-height: 44rpx;
      font-size: 24rpx;
      &.title {
        font-size: 32rpx;
        font-weight: 700;
      }
      &.title_sub {
        color: $second_text_color;
      }
      &.price {
        font-size: 40rpx;
        font-weight: 700;
        color: red;
        line-height: 60rpx;
        display: inline-block;
      }
      &.price_old {
        font-size: 32rpx;
        color: $second_text_color;
        text-decoration: line-through;
        display: inline-block;
        margin-left: 20rpx;
      }
      &.stock {
        font-size: 28rpx;
      }
      &.sell {
        color: #ccc;
      }
    }
  }
  .sku {
    font-size: 24rpx;
    margin: 20rpx 0;
    padding: 20rpx;
    background: white;
    border-radius: 10rpx;
    .value {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .select {
        width: 24rpx;
      }
      .sku-list {
        flex: 1;
        //background: red;
        .item {
          display: inline-block;
          margin-right: 10px;
          background: $main_color;
          color: white;
          padding: 2px 4px;
          font-size: 20rpx;
        }
      }
    }
  }
  .freight {
    font-size: 24rpx;
    margin: 20rpx 0;
    padding: 20rpx;
    background: white;
    border-radius: 10rpx;
  }
  .area {
    margin: 20rpx 0;
    padding: 30rpx;
    background: white;
    border-radius: 10rpx;
    text-align: center;
    color: red;
    font-size: 32rpx;
    font-weight: 700;
  }
  .content {
    font-size: 24rpx;
    margin: 20rpx 0;
    padding: 20rpx;
    background: white;
    border-radius: 10rpx;
    .text {
      line-height: 1.2em;
      margin: 20rpx 0;
    }
    ::v-deep {
      image {
        width: 100%;
      }
    }
    .video-control {
      width: 100%;
      height: 200px;
      background: black;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .video {
      //background: red;
      video {
        width: 100%;
      }
    }
  }
  .footer {
    position: fixed;
    width: 100%;
    height: 110rpx;
    left: 0;
    bottom: 0;
    display: flex;
    background: white;
    padding: 15rpx 40rpx;
    box-sizing: border-box;
    border-top: 1rpx solid #f3f3f3;
    z-index: 9999;
    .icon {
      flex: 1;
      display: flex;
      justify-content: space-between;
      padding: 10rpx 30rpx;
      view {
        color: $second_text_color;
        font-size: 24rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        &.cart {
          //background: red;
          .text {
            position: relative;
            .count {
              position: absolute;
              top: -35rpx;
              right: -15rpx;
            }
          }
        }
      }
    }
    .button {
      flex: 1.8;
      display: flex;
      padding-top: 5rpx;
      view {
        flex: 1;
        height: 70rpx;
        line-height: 70rpx;
        font-size: 28rpx;
        box-sizing: border-box;
        letter-spacing: 2rpx;
        &.cart {
          border: 1rpx solid $main_color;
          color: $main_color;
          border-top-left-radius: 30rpx;
          border-bottom-left-radius: 30rpx;
          text-align: center;
        }
        &.buy {
          background: $main_color;
          color: white;
          border-top-right-radius: 30rpx;
          border-bottom-right-radius: 30rpx;
          text-align: center;
        }
      }
    }
  }
  // pop
  .pop {
    height: 400px;
    padding: 20rpx 20rpx 70rpx 20rpx;
    position: relative;
    overflow-y: auto;
    .reset {
      position: absolute;
      right: 10px;
      top: 10px;
      background: $main_color;
      padding: 15rpx 30rpx;
      border-radius: 5px;
      color: white;
      font-weight: 700;
      font-size: 24rpx;
    }
    .button {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background: $main_color;
      color: white;
      font-size: 30rpx;
      font-weight: 700;
    }
    .main {
      display: flex;
      align-items: center;
      .image {
        width: 200rpx;
        height: 200rpx;
        //background: red;
        overflow: hidden;
        image {
          width: 100%;
          height: 100%;
        }
      }
      .text {
        height: 200rpx;
        //background: red;
        margin-left: 20rpx;
        padding: 0;
        flex: 1;
        font-size: 24rpx;
        flex-direction: column;
        display: flex;
        justify-content: space-around;
        .price, .stock, .quantity {
          //height: 65rpx;
          //line-height: 65rpx;
          //background: blue;
        }
        .price {
          text {
            color: red;
            font-weight: 700;
            font-size: 30rpx;
          }
        }
        .quantity {
          display: flex;
          align-items: center;
          justify-content: start;
          .add, .sub, .value {
            display: inline-block;
            padding: 7.5px 10px;
            font-size: 16px;
            border-radius: 5px;
          }
          .value {
            width: 50px;
            padding: 7.5px 20px;
            background: $background_color;
            color: red;
          }
        }
      }
    }
    .sku-list {
      //background: red;
      min-height: 200px;
      margin-top: 10px;
      margin-bottom: 20px;
      .item {
        margin-bottom: 5px;
        .name {
          font-size: 28rpx;
          font-weight: 700;
        }
        .value {
          margin-top: 5px;
          .value-item {
            display: inline-block;
            background: #ccc;
            margin-right: 15px;
            margin-bottom: 15px;
            padding: 7.5px 15px;
            border-radius: 5px;
            font-size: 24rpx;
            &.active {
              background: $main_color;
            }
            &.disable {
              background: #eee;
            }
            .total {
              margin-left: 5rpx;
            }
          }
        }
      }
    }
    .selected-result {
      margin: 10rpx 0;
      font-size: 24rpx;
      text {
        color: red;
      }
    }
  }
}
</style>
